<template>
  <div class="create-people">
    <el-form
      :model="peopleForm"
      :rules="rules"
      ref="peopleForm"
      label-width="90px"
      class="demo-form"
    >
      <el-form-item label="仓库名称" prop="name">
        <el-input v-model="peopleForm.name" placeholder="请在此输入库房名称"></el-input>
      </el-form-item>
      <!--省-->
      <el-form-item label="选择省份" prop="selectedOptions">
        <el-cascader
          change-on-select
          style="width: 260px"
          size="large"
          :options="options"
          v-model="peopleForm.selectedOptions"
          placeholder="请在此选择省市区"
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item label="仓库地址" prop="address">
        <el-input v-model="peopleForm.address" placeholder="请在此输入库房详细地址"></el-input>
      </el-form-item>
      <el-form-item label="附加属性">
        <el-checkbox-group v-model="peopleForm.storeconfig" size="mini">
          <el-checkbox
            :label="item.config_type"
            :value="item.id"
            border
            v-for="(item,index) in configList"
            :key="index"
          ></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel" class="cancel-btn">取 消</el-button>
      <el-button type="primary" @click="sure('peopleForm')">确 定</el-button>
    </div>
  </div>
</template>

<script>
import Config from "@/config";
import { regionData } from "static/js/regionData";
import { mapGetters } from "vuex";
export default {
  name: "CreateSub",
  props: {
    form: {
      type: Object
    },
    title: {
      type: String,
      default: ""
    },
    flag: {
      type: Boolean
    }
  },
  data() {
    /**
     * 后台判断仓库名称是否重复
     * */
    var isLoginNameDuplicate = name => {
      return new Promise((resolve, reject) => {
        let url = `${Config.DEVICE_MANAGE_URL}/storehouses/query_sub_by_name`;
        let params = {
          name,
          devtype: "nbiot"
        };
        this.$http
          .get(url, params)
          .then(data => resolve(data))
          .catch(e => reject(e));
      });
    };
    /**
     * 验证仓库名称
     * */
    let validateLoginName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入仓库名称"));
      } else if (this.title === "仓库编辑") {
        callback();
      } else {
        isLoginNameDuplicate(value).then(data => {
          // console.log(data)
          if (data) {
            callback(new Error("仓库名已经存在"));
          } else {
            callback();
          }
        });
      }
    };
    return {
      peopleForm: {
        name: "",
        address: "",
        selectedOptions: []
      },
      rules: {
        // name: this.$inputRule("请填写仓库名称"),
        name: [
          { required: true, validator: validateLoginName, trigger: "blur" }
        ],
        address: this.$inputRule("请填写仓库地址"),
        selectedOptions: this.$selectRule("请选择省份", true, "array")
      },
      options: regionData,
      configList: [] // 所有的
    };
  },
  watch: {
    flag: {
      handler(res) {
        if (!res) return;
        // 获取所有类型

        setTimeout(() => {
          this.$refs.peopleForm.resetFields();

          if (this.title === "仓库编辑") {
            this.$http
              .get(
                `${Config.DEVICE_MANAGE_URL}/storehouse_config/query_common?storehouse_id=${this.form.id}`
              )
              .then(res => {
                var config_key = [];
                var id_list = [];
                for (var i = 0; i < res.array.length; i++) {
                  if (
                    this.configList.some(
                      response =>
                        response.config_key === res.array[i].config_key
                    )
                  ) {
                    config_key.push(res.array[i].config_type);
                    id_list.push(res.array[i].id);
                  }
                }
                for (var k in this.form) {
                  this.peopleForm[k] = this.form[k];
                }
                this.id_list = id_list;
                this.config_key = config_key;
                this.$set(this.peopleForm, "storeconfig", config_key);
              })
              .catch(error => {
                console.log(error);
              });
          } else {
            for (var k in this.form) {
              if (k === "storeconfig") {
                this.$set(this.peopleForm, "storeconfig", []);
                continue;
              }
              this.peopleForm[k] = this.form[k];
            }
          }
        }, 500);
      },
      immediate: true
    }
  },
  created() {
    var url = `${Config.DEVICE_MANAGE_URL}/storehouse_config/type`;
    this.$http
      .get(url)
      .then(res => {
        this.configList = res.array;
      })
      .catch(e => {
        console.log(e);
      });
  },
  computed: {
    ...mapGetters("user", {
      role: "getRole",
      user: "getUser"
    })
  },
  methods: {
    cancel() {
      this.$nextTick(() => {
        this.$emit("hide", "cancel");
      });
    },
    sure(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.save();
        } else {
          this.$message({
            message: "格式不正确",
            type: "warning"
          });
          return false;
        }
      });
    },
    /**
     * 保存数据
     * */

    save() {
      if (this.title === "新增仓库") {
        var arr = this.configList.reduce((p, item) => {
          this.peopleForm.storeconfig.includes(item.config_type) &&
            [].push.call(p, {
              config_type: item.config_type,
              config_key: item.config_key
            });
          return p;
        }, []);
        // console.log(JSON.stringify(arr, {}, 4));
        let url = `${Config.DEVICE_MANAGE_URL}/storehouse_config/add`;
        let params = {
          storehouse: {
            name: this.peopleForm.name,
            address: this.peopleForm.address,
            province: this.peopleForm.selectedOptions[0],
            city: this.peopleForm.selectedOptions[1],
            district: this.peopleForm.selectedOptions[2],
            store_level: this.peopleForm.store_level - 0 + 1,
            super_id: this.peopleForm.id,
            lat: this.peopleForm.lat,
            lon: this.peopleForm.lon,
            housetype: "official",
            devtype: Config.objType.devtype,
            country: this.peopleForm.country,
            house_owner: this.user.company,
            country: "86"
          },
          config_list: arr
        };
        this.$http
          .post(url, params)
          .then(data => {
            this.$emit("hide", true);
            this.$refs["peopleForm"].resetFields();
          })
          .catch(e => {});
      } else if (this.title === "新建仓库") {
        let url = `${Config.DEVICE_MANAGE_URL}/storehouses/add`;
        this.$http
          .post(url, {
            name: this.peopleForm.name,
            address: this.peopleForm.address,
            province: this.peopleForm.selectedOptions[0],
            city: this.peopleForm.selectedOptions[1],
            district: this.peopleForm.selectedOptions[2],
            store_level: 1,
            super_id: 1,
            lat: this.peopleForm.lat,
            lon: this.peopleForm.lon,
            housetype: "official",
            devtype: Config.objType.devtype,
            country: this.peopleForm.country,
            house_owner: this.user.company,
            country: "86"
          })
          .then(data => {
            this.$emit("hide", true);
            this.$refs["peopleForm"].resetFields();
          })
          .catch(e => {});
      } else {
        // console.log(this.configList)
        var arr = this.configList.reduce((p, item) => {
          this.peopleForm.storeconfig.includes(item.config_type) &&
            [].push.call(p, {
              config_type: item.config_type,
              config_key: item.config_key,
              // id: this.peopleForm.id
              id: this.id_list[
                this.config_key.findIndex(res => res === item.config_type)
              ]
            });
          return p;
        }, []);
        // console.log(JSON.stringify(arr, {}, 4));

        let url = `${Config.DEVICE_MANAGE_URL}/storehouse_config/modify`;
        //  let url = `http://172.16.79.64:8000/DeviceManage/storehouse_config/modify`;
        let params = {
          storehouse: {
            address: this.peopleForm.address,
            name: this.peopleForm.name,
            city: this.peopleForm.selectedOptions[1]
              ? this.peopleForm.selectedOptions[1]
              : "",
            district: this.peopleForm.selectedOptions[2]
              ? this.peopleForm.selectedOptions[2]
              : "",
            province: this.peopleForm.selectedOptions[0],
            id: this.peopleForm.id,
            user_info: this.user.loginName,
            user_id: this.user.id
          },
          config_list: arr.length ? arr : undefined
        };
        this.$http
          .put(url, params)
          .then(data => {
            this.$emit("hide", true);
            this.$refs["peopleForm"].resetFields();
          })
          .catch(e => {
            this.$message.error(`${e}`)
          });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.create-people {
  .el-input,
  .el-select {
    width: 260px;
  }
  .manage-district {
    height: auto;
  }
  .manage-district /deep/ .el-form-item__content {
    line-height: 32px;
  }
  .el-checkbox.is-bordered.el-checkbox--mini {
    margin-top: 5px;
  }
  /deep/ .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #eb3838;
  }
  .el-checkbox.is-bordered.is-checked {
    border-color: #eb3838;
  }
  .dialog-footer {
    height: 28px;
    text-align: center;
    margin: 60px 0 0 0;
    .el-button {
      padding: 7px 27px;
      height: 28px;
      width: 86px;
    }
  }
}
</style>
